import { Rect } from "./Rect.js";
// let d1 = new Rect(0, 0, "red")
import { Food } from "./food.js"
let food = new Food();
export class Snake {
  constructor() {
    // 蛇的身体  
    this.bodyArr = [];
    this.createBody();
    // this.addDomain();
    this.move()
    // 定义蛇头方向
    this.dir = "right"
  }
  createBody() {
    for (let i = 0; i < 3; i++) {
      if (i == 2) {
        this.bodyArr.push(new Rect(i * 50, 0, "red"));
      } else {
        this.bodyArr.push(new Rect(i * 50, 0, "blue"));

      }
    }
  }

  // 碰撞检测
  isCrash(box1Ele, box2Ele) {
    // x轴判断相关坐标
    var minx2 = box2Ele.offsetLeft;
    var maxx2 = box2Ele.offsetLeft + box2Ele.offsetWidth;
    var minx1 = box1Ele.offsetLeft;
    var maxx1 = box1Ele.offsetLeft + box1Ele.offsetWidth;

    // y轴判断相关坐标

    var miny2 = box2Ele.offsetTop;
    var maxy2 = box2Ele.offsetTop + box2Ele.offsetHeight;
    var miny1 = box1Ele.offsetTop;
    var maxy1 = box1Ele.offsetTop + box1Ele.offsetHeight;

    if (maxx1 > minx2 && minx1 < maxx2 && maxy1 > miny2 && miny1 < maxy2) {
      return true;
    } else {
      return false;
    }

  }
  // addDomain(){
  //     for(let i=0;i<this.bodyArr.length;i++){
  //         map1.ele.appendChild(this.bodyArr[i].ele);
  //     }
  // }
  move() {
    setInterval(() => {
      let head = this.bodyArr[this.bodyArr.length - 1];
      let pos = {
        x: parseInt(head.ele.style.left),
        y: parseInt(head.ele.style.top)
      }
      switch (this.dir) {
        case "right":
          // 1.蛇头移动一个距离 
          head.ele.style.left = parseInt(head.ele.style.left) + 50 + "px";
          break;
        case "left":
          // 1.蛇头移动一个距离 
          head.ele.style.left = parseInt(head.ele.style.left) - 50 + "px";
          break;
        case "up":
          // 1.蛇头移动一个距离 
          head.ele.style.top = parseInt(head.ele.style.top) - 50 + "px";
          break;
        case "down":
          // 1.蛇头移动一个距离 
          head.ele.style.top = parseInt(head.ele.style.top) + 50 + "px";
          break;
      }

      // 判断蛇头和食物是否碰撞？
      console.log(this.isCrash(head.ele, food.rect.ele));
      if (this.isCrash(head.ele, food.rect.ele)) {
        // 碰了之后 1.蛇身体加一个   2. 食物消失 ，重新生成一个 ；
        food.rect.ele.remove();
        food = new Food();
      } else {
        // 2.把蛇尾巴删除；
        let res = this.bodyArr.shift();  // 把数组里的rect对象删除
        res.ele.remove(); // 把rect 对象里的元素删除掉；
      }



      // 3.在原来蛇头的位置 添加一个元素；
      this.bodyArr.splice(this.bodyArr.length - 1, 0, new Rect(pos.x, pos.y, "blue"));
    }, 1000);


  }
}